<template>
  <div class="app-container">
    <el-form :inline="true"  class="demo-form-inline" style="margin-top: 2%">
      <el-row :gutter="0">
        <el-col :span="6">
          <el-form-item label="角色名称">
            <el-input size="mini" v-model="ParamsEntity.roleName" placeholder="角色名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="角色状态">
            <!--<el-input size="mini" v-model="searchParams.phone" placeholder="手机号"></el-input>-->
            <el-select v-model="ParamsEntity.status" clearable placeholder="请选择"  size="mini">
              <el-option label="正常" value="0"></el-option>
              <el-option label="停用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item  size="mini" label="创建时间">
            <!-- <el-input v-model="searchParams.createTime" placeholder="创建时间"></el-input>-->
            <el-date-picker
              v-model="ParamsEntity.createTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="创建时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row >
        <el-button  type="primary" @click="onSubmit" size="small" icon="el-icon-search" v-hasPermi="['sys:role:search']">搜索</el-button>
        <el-button  type="success" @click="add" size="small" icon="el-icon-plus" v-hasPermi="['sys:role:add']">新增</el-button>
        <el-button  type="danger" @click="deleteBatch" size="small" icon="el-icon-delete" :disabled="deleteFlag" v-hasPermi="['sys:role:deletebatch']">批量删除</el-button>
        <el-button  type="warning" @click="exportExcel" size="small" icon="el-icon-download" v-hasPermi="['sys:role:export']">导出</el-button>
    </el-row>
    <template>
      <el-table
        :data="roleList"
        v-loading="loading"
        element-loading-text="拼命加载中"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="角色名"
          prop="roleName"
          width="180">
        </el-table-column>
        <el-table-column
          label="角色字符串"
          prop="roleKey"
          width="180">
        </el-table-column>
        <el-table-column
          label="角色状态"
          prop="status"
          :formatter="stateFormat"
          width="180">
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          :formatter="dateFormat"
          width="180">
        </el-table-column>
        <el-table-column
          label="创建者"
          prop="updateBy"
          width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"  v-hasPermi="['sys:role:edit']">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="scope.row.roleKey ==='admin'?deleteShowFlag=false:true"
              @click="handleDelete(scope.$index, scope.row)"  v-hasPermi="['sys:role:delete']">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
    </template>

    <div class="page">

      <Pagination v-show="total>0"
                  :total="total"
                  :page.sync="ParamsEntity.pageNum"
                  :limit.sync="ParamsEntity.pageSize"
                  @pagination="queryRoleList" />
    </div>
    <el-dialog
      title="新增角色"
      :visible.sync="addFlag"
      width="500px" append-to-body>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="80px">
        <el-row>

          <el-col :span="24">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                placeholder="请输入角色名称"
                v-model="roleForm.roleName"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色字符" prop="roleKey">
              <el-input
                placeholder="请输入角色字符串"
                v-model="roleForm.roleKey"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示顺序" prop="roleSort">
              <el-input-number v-model="roleForm.roleSort" controls-position="right"  :min="1" ></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="权限菜单" >
              <el-tree
                :data="treeMenu"
                show-checkbox
                node-key="id"
                ref="tree"
                @check="selectedMenus"
                :default-checked-keys="roleIds"
                :props="defaultProps">
              </el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="roleForm.remark"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="addFlag = false">取 消</el-button>
                <el-button type="primary" @click="addSubmit">确 定</el-button>
            </span>
    </el-dialog>
    <el-dialog
      title="编辑角色"
      :visible.sync="editFlag"
      width="500px" append-to-body>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="80px">
        <el-row>

          <el-col :span="24">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                placeholder="请输入角色名称"
                v-model="roleForm.roleName"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色字符" prop="roleKey">
              <el-input
                placeholder="请输入角色字符串"
                v-model="roleForm.roleKey"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示顺序" prop="roleSort">
              <el-input-number v-model="roleForm.roleSort" controls-position="right"  :min="1" ></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="权限菜单" >
              <el-tree
                :data="treeMenu"
                show-checkbox
                node-key="id"
                ref="tree"
                @check="selectedMenus"
                :default-checked-keys="roleIds"
                :props="defaultProps">
              </el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="roleForm.remark"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="editFlag = false">取 消</el-button>
                <el-button type="primary" @click="edit">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import {queryRoleList,addRole,deleteRole,exportRoleList,queryRoleById,editRole} from "@/api/role/role"
  import {getTreeMenu} from '@/api/menu/menu'
  import Cookies from "js-cookie";
  export default {
    name: "index",
    inject: ['reload'],
    components:{
      Pagination
    },
    data() {
      return {
        // 总条数
        total: 0,
        multipleSelection: [],
        addFlag:false,
        roleForm:{
          roleId:"",
          roleName:"",
          roleKey:"",
          roleSort:'',
          status:'',
          delFlag:'',
          createBy:'',
          createTime:'',
          updateBy:'',
          updateTime:'',
          remark:'',
          //选中的菜单
          menuIds:[],
          roleIds:[]
        },
        imageUrl: '',
        rules: {
          roleName: [
            {required: true, message: "角色名不能为空", trigger: "blur"}
          ],
          roleKey: [
            {required: true, message: "角色字符串不能为空", trigger: "blur"}
          ],
          roleSort: [
            {required: true, message: "显示顺序不能为空", trigger: "blur"}
          ]
        },
        deleteFlag:true,
        /**
         * 控制删除按钮
         */
        deleteShowFlag:false,
        arrObj : [],
        editFlag:false,
        delFlag:false,
        currentPage: 1,
        ParamsEntity:{
          roleName:null,
          status:null,
          createTime:null,
          pageNum: 1,
          pageSize: 10,
        },
        roleList:[],
        //dialog对话框树状菜单显示
        treeMenu:[],
        //编辑角色回显菜单
        roleIds:[],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 遮罩层
        loading: true,
      }
    },
    created(){
      this.queryRoleList();
    },
    methods: {
      queryRoleList(){
        this.loading = true;
        queryRoleList(this.ParamsEntity).then(res=>{
          this.roleList = res.data.result;
          this.total = parseInt(res.data.total);
          this.loading = false;
        })
      },
       handleEdit(index, row) {
         getTreeMenu().then(response=>{
           this.treeMenu = response.data;
         });
        this.roleIds = [];
        this.editFlag = true;
         queryRoleById(row.roleId).then(res=>{
          this.roleForm = res.data.sysRole;
           let arr = res.data.sysRoleMenus.map(item => item.menuId);//后端返回的所有id
           arr.forEach(i=>{
             let node = this.$refs.tree.getNode(i);//根据id 拿到 Tree 组件中的node的所有信息
             if(node.isLeaf){//node.isLeaf：判断当前节点是否为子节点
               this.$refs.tree.setChecked(node, true);//如果是子节点，就把状态设置成选中
             }
           });
        });

      },
      handleDelete(index, row) {
        this.roleForm.roleIds=[];
      this.roleForm.roleIds.push(row.roleId);
        deleteRole( this.roleForm).then(res=>{
          if (res.code===200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.deleteFlag = true;
            this.reload();
          }

        });
      },
      onSubmit() {
        this.queryRoleList();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        if (val.length>0) {
          this.deleteFlag = false;
          let deleteArray = this.multipleSelection.filter(item=>item.roleKey!=="admin");
          this.multipleSelection.forEach((item,index,arr)=>{
              if ("admin"===item.roleKey) {
                this.$notify({
                  title: '警告',
                  message: '管理员角色不能删除，请重新选择',
                  type: 'warning'
                });
                this.deleteFlag = true;
              }
            },
            deleteArray.forEach((item,index,arr)=>{
              this.arrObj.push(item.roleId);
            })
          );
        }else {
          this.deleteFlag = true;
          this.$notify({
            title: '警告',
            message: '请选中记录删除',
            type: 'warning'
          });
        }
      },
      add() {
        this.roleForm.roleName = "";
        this.roleForm.roleKey="";
        this.addFlag = true;
        getTreeMenu().then(res=>{
          this.treeMenu = res.data;
        });
      },
      addSubmit() {

        this.$refs.roleForm.validate(valid => {
          if (valid) {
            addRole(this.roleForm).then(res=>{
              if (res.code===200) {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
                this.addFlag = false;
                this.reload();
              }
            })
          }
        });
      },

      deleteBatch() {
        this.roleForm.roleIds = this.arrObj;
        const uniqueSet = new Set(this.roleForm.roleIds);
        this.roleForm.roleIds = [...uniqueSet];
        deleteRole(this.roleForm).then(res=>{
          if (res.code===200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.deleteFlag = true;
            this.reload();
          }

        });

      },
      exportExcel() {
        exportRoleList().then(res=>{
          let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
          let downloadElement = document.createElement('a');
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = 'result.xls'; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        })
      },
      edit() {
        editRole(this.roleForm).then(res=>{
          if (res.code===200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.editFlag = true;
            this.reload();
          }
        })

      },
      dateFormat(row){

        let datetime = row.createTime;
        if(datetime){
          datetime = new Date(datetime);
          let y = datetime.getFullYear() + '-';
          let mon = datetime.getMonth()+1 + '-';
          let d = datetime.getDate();
          return y + mon + d;
        }
        return ''

      },
      stateFormat(row) {
        return row.status==='0'?'正常':'停用';
      },
      selectedMenus(checkedNodes,checkedKeysList) {
        let checkedKeys = checkedKeysList.checkedKeys;
        let halfCheckedKeys = checkedKeysList.halfCheckedKeys;
        checkedKeys.push(...halfCheckedKeys);
        this.roleForm.menuIds = checkedKeys;
      }

    }
  }
</script>

<style lang="scss" >
  .container {
    display: flex;
    flex-direction: column;
  }
  .page {
    display: flex;
    flex-direction: row;
    margin-left: 91%;
    margin-top: 1%;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-switch__label--left{
    position: relative;
    left: 46px;
    color: #fff;
    z-index: -1111;
  }
  .el-switch__label--right{
    position: relative;
    right: 46px;
    color: #fff;
    z-index: -1111;
  }
  .el-switch__label.is-active{
    z-index: 1111;
    color: #fff;
  }
  .el-switch__label--left{
    position: relative;
    left: 46px;
    color: #fff;
    z-index: -1111;
  }
  .el-switch__label--right{
    position: relative;
    right: 46px;
    color: #fff;
    z-index: -1111;
  }
  .el-switch__label--right.is-active{
    z-index: 1111;
    color: #fff !important;
  }
  .el-switch__label--left.is-active{
    z-index: 1111;
    color: #9c9c9c !important;
  }
</style>
